package com.sz.flowable.service;

import com.sz.flowable.dto.CompleteTaskDTO;
import com.sz.flowable.dto.StartProcessDTO;
import com.sz.flowable.dto.TaskDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.api.Task;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yinan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BpmnServiceImpl implements BpmnService {

    private final RuntimeService runtimeService;

    private final TaskService taskService;

    @Override
    public String startProcess(StartProcessDTO dto) {
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(
                dto.getProcessDefinitionKey(), dto.getBusinessKey(), dto.getVariables());
        return instance.getId();
    }

    @Override
    public List<TaskDTO> getTodoList(String username) {
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee(username)
                .orderByTaskCreateTime().desc()
                .list();
        return tasks.stream().map(task ->
                new TaskDTO(task.getId(), task.getName(), task.getProcessInstanceId())
        ).collect(Collectors.toList());
    }

    @Override
    public void completeTask(CompleteTaskDTO dto) {
        taskService.complete(dto.getTaskId(), dto.getVariables());
    }
}
